package com.lbs.jiepiaisi.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.AboutUsActivity;
import com.lbs.jiepiaisi.activity.AccountProblemActivity;
import com.lbs.jiepiaisi.activity.DownLoadDialogActivity;
import com.lbs.jiepiaisi.activity.ResetPwdActivity;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.manager.SharePreferenceManager;
import com.lbs.jiepiaisi.service.VersionService;
import com.lbs.jiepiaisi.utils.AccountEvent;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.Constant1;
import com.lbs.jiepiaisi.utils.ImageUtil;
import com.lbs.jiepiaisi.utils.IntentUtil;
import com.lbs.jiepiaisi.utils.SpUtil;
import com.lbs.jiepiaisi.utils.UrlUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;


public class MineFragment extends BaseFragment implements WeatherSearch.OnWeatherSearchListener,AMapLocationListener{

    private ImageView imageView;
    private Bitmap bitmap;
    private ImageView image_setting;
    //意见反馈
    private LinearLayout line_yijianfankui;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //位置和天气
    private TextView infoDisWeather;
    //天气温度
    private TextView infoTemp;
    private TextView mDeptName;
    private String city;
    private final int REQUEST_CODE = 1000;
    private String phone = "053158051562";
    private TextView mTvVersion;
    //public SharePreferenceManager mSharePreference = SharePreferenceManager.getInstance(mContext);

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_mine,null);
        return view;
    }

    @Override
    protected void getExtras(View view) {
        EventBus.getDefault().register(this);
        initLocation();
    }

    @Override
    protected void findView(View view) {
        imageView = view.findViewById(R.id.image_background);
        //从资源中获取Bitmap
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.my_photo);
        //设置
        image_setting= view.findViewById(R.id.image_setting);
        //高斯模糊
        vague();
        infoDisWeather = view.findViewById(R.id.info_dis_weather);
        infoTemp = view.findViewById(R.id.tv_temp);
        mDeptName = view.findViewById(R.id.tv_dept_name);

        //mDeptName.setText(mSharePreference.getString(Constant.ACCOUNT_DEPT_NAME,""));
        mDeptName.setText((String)SpUtil.get(Constant1.DEPT_NAME,""));
        mTvVersion = view.findViewById(R.id.mTvVersion);
        mTvVersion.setText(getVersionName());
    }

    @Override
    protected void setListener(View view) {
        // 修改密码
        view.findViewById(R.id.lin_reset_pwd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ResetPwdActivity.class);
                intent.putExtra("type", 0);
                intent.putStringArrayListExtra("mData", new ArrayList<String>());
                startActivity(intent);
            }
        });

        // 意见反馈
        view.findViewById(R.id.ll_feedback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    IntentUtil.gotoActivity(mActivity, AccountProblemActivity.class,false);
                }
            }
        });

        // 联系我们
        view.findViewById(R.id.lin_contract_us).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    calUs(phone);
                }
            }
        });

        // 退出平台
        view.findViewById(R.id.lin_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });

        // 关于我们
        view.findViewById(R.id.about_us_lin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    IntentUtil.gotoActivity(mActivity, AboutUsActivity.class,false);
                }
            }
        });

        // 版本检测
        view.findViewById(R.id.lin_version).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {//检查更新
                    VersionParams.Builder builder = new VersionParams.Builder()
                            .setRequestUrl(UrlUtil.CHECK_VERSION)
                            .setForceRedownload(true)
                            .setShowNotification(true)
                            .setService(VersionService.class);
                    //CustomVersionDialogActivity.customVersionDialogIndex = 2;
                    builder.setCustomDownloadActivityClass(DownLoadDialogActivity.class);
                    AllenChecker.startVersionCheck(mActivity.getBaseContext(), builder.build());
                }catch (Exception e){

                }
            }
        });
    }

    /**
     * 调用拨号功能
     * @param phone 电话号码
     */
    public void calUs(String phone){
        /**
         * 判断有无打电话权限
         * */
        if(ContextCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            ///没有则请求获取权限，示例权限是：相机权限和定位权限，需要其他权限请更改或者替换
            ActivityCompat.requestPermissions(mActivity,new String[]{Manifest.permission.CALL_PHONE },REQUEST_CODE);
        }else {
            Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
            startActivity(intent);
        }
    }
    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_CODE:
                if(grantResults.length  >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
                    startActivity(intent);
                }else {
                    Toast.makeText(mContext,"您拒绝了拨打电话权限,请手动获取或重装软件",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void vague() {
        //异步处理
        new Thread(new Runnable() {
            @Override
            public void run() {
                //高斯模糊处理图片
                bitmap = ImageUtil.doBlur(bitmap,30,false);
                //处理完成后返回主线程
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }

    private String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = mActivity.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(mActivity.getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    //接收修改密码结果后退出重新登录
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(AccountEvent accountEvent) {
        mActivity.finish();
    }


    public void initLocation(){
        mlocationClient = new AMapLocationClient(mContext);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    public void onWeatherLiveSearched(LocalWeatherLiveResult localWeatherLiveResult, int i) {
        infoDisWeather.setText(city + " " +localWeatherLiveResult.getLiveResult().getWeather());
        infoTemp.setText(localWeatherLiveResult.getLiveResult().getTemperature() + "°C");
    }

    @Override
    public void onWeatherForecastSearched(LocalWeatherForecastResult localWeatherForecastResult, int i) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        city = aMapLocation.getCity();
        Log.e("TAG","地理位置信息："+city);
        getWeather(city);
        infoDisWeather.setText(city);

    }

    public void getWeather(String city){
        //检索参数为城市和天气类型，实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST
        WeatherSearchQuery mquery = new WeatherSearchQuery(city, WeatherSearchQuery.WEATHER_TYPE_LIVE);
        WeatherSearch mweathersearch=new WeatherSearch(mContext);
        mweathersearch.setOnWeatherSearchListener((WeatherSearch.OnWeatherSearchListener)MineFragment.this);
        mweathersearch.setQuery(mquery);
        mweathersearch.searchWeatherAsyn(); //异步搜索
    }
}
